import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { appConfig } from '@/config'
import { logger } from '@/utils/logger'
import { articleService } from '@/services/articleService'

export const useArticleStore = defineStore('article', () => {
  // 状态
  const articles = ref([])
  const currentArticle = ref(null)
  const searchResults = ref([])
  const searchQuery = ref('')
  const searchInfo = ref({})
  const chapters = ref([])
  const favorites = ref([])
  const searchHistory = ref([])
  const loading = ref(false)
  const error = ref(null)
  const pagination = ref({
    page: 1,
    per_page: 20,
    total: 0,
    pages: 0
  })
  
  // 计算属性
  const articlesCount = computed(() => articles.value.length)
  const chaptersCount = computed(() => chapters.value.length)
  const hasSearchResults = computed(() => searchResults.value.length > 0)
  const hasFavorites = computed(() => favorites.value.length > 0)
  const hasSearchHistory = computed(() => searchHistory.value.length > 0)
  
  const isArticleFavorited = computed(() => (articleNumber) => {
    return favorites.value.some(fav => fav.article_number === articleNumber)
  })
  
  // 方法
  async function searchArticles(query, page = 1, per_page = 20) {
    if (!query.trim()) return
    
    try {
      loading.value = true
      error.value = null
      
      const response = await articleService.searchArticles(query, { page, per_page })
      
      searchResults.value = response.articles
      searchInfo.value = response.searchInfo
      pagination.value = response.pagination
      searchQuery.value = query
      
      // 添加到搜索历史
      await addToSearchHistory(query, response.searchInfo?.result_count || 0)
      
      logger.userAction('搜索文章', { query, resultCount: response.articles.length })
      return response
    } catch (err) {
      error.value = err.message || '搜索失败'
      logger.error('搜索文章失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  async function fetchChapters() {
    loading.value = true
    error.value = null
    
    try {
      const chapters = await articleService.getChapters()
      chapters.value = chapters
      logger.debug('获取章节列表成功', { count: chapters.length })
      return chapters
    } catch (err) {
      error.value = err.message || '获取章节列表失败'
      logger.error('获取章节列表失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }
  
  async function fetchArticlesByChapter(chapterNumber, page = 1, limit = 50) {
    loading.value = true
    error.value = null
    
    try {
      const response = await articleService.getArticlesByChapter(chapterNumber, page, limit)
      
      if (page === 1) {
        articles.value = response.data
      } else {
        articles.value.push(...response.data)
      }
      
      return response
    } catch (err) {
      error.value = err.message || '获取条文列表失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  async function fetchArticleById(articleId) {
    loading.value = true
    error.value = null
    
    try {
      const response = await articleService.getArticleById(articleId)
      currentArticle.value = response.data
      return response.data
    } catch (err) {
      error.value = err.message || '获取条文详情失败'
      throw err
    } finally {
      loading.value = false
    }
  }
  
  function clearCurrentArticle() {
    currentArticle.value = null
  }
  
  function clearArticles() {
    articles.value = []
  }
  
  // 收藏相关方法
  async function addToFavorites(article) {
    try {
      await articleService.addFavorite(article.article_number)
      
      if (!favorites.value.find(fav => fav.article_number === article.article_number)) {
        favorites.value.push({
          article_number: article.article_number,
          title: article.title || article.article_number,
          created_at: new Date().toISOString()
        })
        saveFavoritesToStorage()
      }
      
      logger.userAction('添加收藏', { articleNumber: article.article_number })
    } catch (err) {
      logger.error('添加收藏失败:', err)
      throw err
    }
  }
  
  async function removeFromFavorites(articleNumber) {
    try {
      await articleService.removeFavorite(articleNumber)
      
      const index = favorites.value.findIndex(fav => fav.article_number === articleNumber)
      if (index > -1) {
        favorites.value.splice(index, 1)
        saveFavoritesToStorage()
      }
      
      logger.userAction('移除收藏', { articleNumber })
    } catch (err) {
      logger.error('移除收藏失败:', err)
      throw err
    }
  }
  
  // 搜索历史相关方法
  async function addToSearchHistory(query, resultCount = 0) {
    if (!query.trim()) return
    
    try {
      // 调用后端API保存搜索历史
      await articleService.saveSearchHistory(query, resultCount)
      
      const historyItem = {
        query,
        result_count: resultCount,
        created_at: new Date().toISOString()
      }
      
      // 移除重复项
      searchHistory.value = searchHistory.value.filter(item => item.query !== query)
      // 添加到开头
      searchHistory.value.unshift(historyItem)
      
      // 限制历史记录数量
      if (searchHistory.value.length > 20) {
        searchHistory.value = searchHistory.value.slice(0, 20)
      }
      
      saveSearchHistoryToStorage()
      logger.userAction('保存搜索历史', { query, resultCount })
    } catch (err) {
      logger.error('保存搜索历史失败:', err)
      // 即使后端保存失败，也要保存到本地存储
      const historyItem = {
        query,
        result_count: resultCount,
        created_at: new Date().toISOString()
      }
      
      searchHistory.value = searchHistory.value.filter(item => item.query !== query)
      searchHistory.value.unshift(historyItem)
      
      if (searchHistory.value.length > 20) {
        searchHistory.value = searchHistory.value.slice(0, 20)
      }
      
      saveSearchHistoryToStorage()
    }
  }
  
  async function fetchSearchHistory() {
    try {
      loading.value = true
      error.value = null
      
      const history = await articleService.getSearchHistory()
      searchHistory.value = history || []
      
      // 同步到本地存储
      saveSearchHistoryToStorage()
      
      logger.debug('获取搜索历史成功', { count: searchHistory.value.length })
      return searchHistory.value
    } catch (err) {
      error.value = err.message || '获取搜索历史失败'
      logger.error('获取搜索历史失败:', err)
      
      // 如果后端获取失败，尝试从本地存储加载
      try {
        const saved = localStorage.getItem(appConfig.storageKeys.searchHistory)
        if (saved) {
          searchHistory.value = JSON.parse(saved)
          logger.debug('从本地存储加载搜索历史', { count: searchHistory.value.length })
        }
      } catch (localErr) {
        logger.error('从本地存储加载搜索历史失败:', localErr)
      }
      
      throw err
    } finally {
      loading.value = false
    }
  }

  async function clearSearchHistory() {
    try {
      await articleService.clearSearchHistory()
      searchHistory.value = []
      localStorage.removeItem(appConfig.storageKeys.searchHistory)
      logger.userAction('清空搜索历史')
    } catch (err) {
      logger.error('清空搜索历史失败:', err)
      throw err
    }
  }
  
  // 本地存储方法
  function saveFavoritesToStorage() {
    try {
      localStorage.setItem(appConfig.storageKeys.favorites, JSON.stringify(favorites.value))
    } catch (err) {
      logger.error('保存收藏失败:', err)
    }
  }
  
  function saveSearchHistoryToStorage() {
    try {
      localStorage.setItem(appConfig.storageKeys.searchHistory, JSON.stringify(searchHistory.value))
    } catch (err) {
      logger.error('保存搜索历史失败:', err)
    }
  }
  
  function initializeFromStorage() {
    // 加载收藏
    try {
      const saved = localStorage.getItem(appConfig.storageKeys.favorites)
      if (saved) {
        favorites.value = JSON.parse(saved)
      }
    } catch (err) {
      logger.error('加载收藏失败:', err)
    }
    
    // 加载搜索历史
    try {
      const saved = localStorage.getItem(appConfig.storageKeys.searchHistory)
      if (saved) {
        searchHistory.value = JSON.parse(saved)
      }
    } catch (err) {
      logger.error('加载搜索历史失败:', err)
    }
    
    logger.debug('文章数据初始化完成')
  }
  
  function clearError() {
    error.value = null
  }
  
  return {
    // 状态
    articles,
    currentArticle,
    searchResults,
    searchQuery,
    searchInfo,
    chapters,
    favorites,
    searchHistory,
    loading,
    error,
    pagination,
    
    // 计算属性
    articlesCount,
    chaptersCount,
    hasSearchResults,
    hasFavorites,
    hasSearchHistory,
    isArticleFavorited,
    
    // 方法
    searchArticles,
    fetchChapters,
    fetchArticlesByChapter,
    fetchArticleById,
    addToFavorites,
    removeFromFavorites,
    addToSearchHistory,
    fetchSearchHistory,
    clearSearchHistory,
    initializeFromStorage,
    clearCurrentArticle,
    clearArticles,
    clearError,
  }
})
